package spring_toby.vol1.ch1.selftest.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import spring_toby.vol1.ch1.selftest.domain.User;


public class UserDao
{
	private DataSource dataSource;

	public void setDataSource(DataSource dataSource)
	{
		this.dataSource = dataSource;
	}

	public void add(User user) throws ClassNotFoundException, SQLException
	{
		Connection c = this.dataSource.getConnection();

		PreparedStatement ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
		ps.setString(1, user.getId());
		ps.setString(2, user.getName());
		ps.setString(3, user.getPassword());

		ps.executeUpdate();

		ps.close();
		c.close();
	}

	public User get(String id) throws ClassNotFoundException, SQLException
	{
		Connection c = this.dataSource.getConnection();
		PreparedStatement ps = c.prepareStatement("select * from users where id = ?");
		ps.setString(1, id);

		ResultSet rs = ps.executeQuery();
		rs.next();
		User user = new User();
		user.setId(rs.getString("id"));
		user.setName(rs.getString("name"));
		user.setPassword(rs.getString("password"));

		rs.close();
		ps.close();
		c.close();

		return user;
	}

	public void del(String id) throws ClassNotFoundException, SQLException
	{
		Connection c = this.dataSource.getConnection();

		PreparedStatement ps = c.prepareStatement("delete from users where id = ?");
		ps.setString(1, id);

		ps.executeUpdate();

		ps.close();
		c.close();
	}
}
